<template>
  <view class="layout">
    <view class="goBack" @click="goBack" :style="{top:(getStatusBarHeight()-2)+'px'}">
      <uni-icons type="back" color="#fff" size="20"></uni-icons>
    </view>
    <!-- <score-view :score="score"></score-view> -->
    <view class="content">
      <view class="title">
        <view class="bg">
          <image src="../../static/bg_title.png" mode="aspectFill"></image>
          <image class="wallet" src="../../static/ic_wallet.png" v-if="false" mode="aspectFill"></image>
        </view>
        <view class="info" :style="{top:20+'px'}">
          <view class="title1">
            {{itemDetail.name + "卡"}}
          </view>
          <view class="title2">
            赶快来刮一下吧
          </view>
        </view>
      </view>
      <view class="usernums" :style="{ height : numHeight + 'rpx'}">
        <view class="items">
          <view class="item" v-for="item in userNums"
                :style="{ border: item.isWin && isShowWin? '2px solid red' : 'none' }">
            <view class="winnum">
              {{currentText}}
            </view>
          </view>
        </view>
        <canvas v-if="!isShowWin" class="canvas2" id="canvas2" canvas-id="canvas2" @touchstart="touchstart2"
                @touchmove="touchmove2" @touchend="touchend2"></canvas>
      </view>
      <view class="footer">
      </view>
    </view>
	<uni-popup ref="resultPopup" :is-mask-click="false" mask-background-color="rgba(0,0,0,0.8)">
	  <view class="resultPopup">
	    <view class="bg win" v-if="winMoney!== 0">
	      <view class="text">祝您-{{currentText}}</view>
	    </view>
	    <view class="bg loser" v-else>
	      <view class="text">{{'再来一次'}}</view>
	    </view>
	    <view class="submitBtn" @click="onSubmit">
	      <button type="primary">再来一次</button>
	    </view>
	    <view class="close" @click="closeResult">
	      <uni-icons type="close" color="#eee" size="40"></uni-icons>
	    </view>
	  </view>
	</uni-popup>
  </view>
 
</template>

<script>
  import {
    getStatusBarHeight,
    getNavBarHeight,
    rpxToPx,
    pxToRpx
  } from "@/utils/system.js";
  import {
    onLoad,
    onShow,
    onReady
  } from "@dcloudio/uni-app";
  import {
    onMounted,
    getCurrentInstance
  } from 'vue';
  import {
    onShareAppMessage,
    onShareTimeline
  } from "@dcloudio/uni-app";
  import {
    getUserScore,
    SignInGetScore,
    addUserScore
  } from "../../utils/common";

  export default {
    data() {
      return {
        title: '',
        titleHeight: 0,
        numHeight: 0,
        isShowWin: false,
        openNums: [],
        userNums: [],
        viewWidth: 0,
        viewHeight: 0,
        score: 0,
        ctx: null,
        viewWidth2: 0,
        viewHeight2: 0,
        ctx2: null,
        points: [],
        points2: [],
        winPoints: 0,
        userPoints: 0,
        resultPopup: null,
        winMoney: 0,
        itemNums: 0,
        currentText: '平安喜乐',
        itemDetail: {},
        // 刮奖音效相关
        innerAudioContext: uni.createInnerAudioContext()
      };
    },
    created() {
      this.innerAudioContext.autoplay = false;
      this.innerAudioContext.src = "/static/audio/gua.m4a";
    },
    onLoad(e) {
      this.itemDetail = JSON.parse(e.itemDetail);
      this.title = e.title;
      this.titleHeight = getStatusBarHeight() + 10;
      console.log(uni.getSystemInfoSync().screenHeight + ',' + uni.getSystemInfoSync().pixelRatio);
      this.numHeight = pxToRpx(uni.getSystemInfoSync().screenHeight - getNavBarHeight()) - (350 + 20);
      this.itemNums = 1;
      this.creatNums();
    },
    onShow() {
      this.score = getUserScore();
    },
    onMounted() {
      this.drawInit2();
    },
    methods: {
      goBack() {
        // drawInit();
        uni.navigateBack({
          success: () => {
          },
          fail: () => {
            uni.reLaunch({
              url: '/pages/index/shouye'
            });
          }
        });
      },
      closeResult() {
        this.$refs.resultPopup.close();
      },
      onSubmit() {
        // if (this.score >= 50) {
        //  const myScore = addUserScore(-50);
        //  this.score = myScore;
        this.$refs.resultPopup.close();
        this.winMoney = 0;
        // creatNums();
        // drawInit2();
        this.isShowWin = false;
        this.ctx = null;
        this.points = [];
        this.ctx2 = null;
        this.points2 = [];
        this.winPoints = 0;
        this.userPoints = 0;
        setTimeout(() => {
          this.creatNums();
          this.drawInit2();
        }, 500);
      },
      creatNums() {
        let list = [];
        if (this.itemDetail.winNum) {
          list = this.itemDetail.winNum;
        } else {
          list = ["平安喜乐", "皆大欢喜", "喜气洋洋", "国泰民安", "万事如意", "一帆风顺", "平安喜乐", "安居乐业", "吉祥如意", "平安健康", "四海升平"];
        }
        const randomIndex = this.getRandomNum(10);
        console.log('randomIndex:' + randomIndex);
        const random = this.getRandomNum(100);
        this.currentText = list[randomIndex];
        const item = {
          num: list[randomIndex],
          money: 100,
          isWin: true
        };
        this.userNums.push(item);
        this.winMoney = 100;
      },
      getRandomNum(num) {
        return Math.floor(Math.random() * num) + 1;
      },
      touchstart2(e) {
        let startX = e.changedTouches[0].x;
        let startY = e.changedTouches[0].y;
        let startPoint = {
          x: startX,
          y: startY
        };
        //存点 一起画
        this.points2.push(startPoint);
        //每次触摸开始，开启新的路径F
        this.ctx2.beginPath();
      },
      touchmove2(e) {
        let moveX = e.changedTouches[0].x;
        let moveY = e.changedTouches[0].y;
        let movePoint = {
          x: moveX,
          y: moveY
        };
        this.points2.push(movePoint);
        this.userPoints += 1;
        if (this.points2.length >= 2) {
          this.drawLine2();
        }
        this.innerAudioContext.play();
      },
      touchend2(e) {
        this.points2 = [];
        this.chechShowAnwser();
      },
      chechShowAnwser() {
        console.log(this.winPoints + ',' + this.userPoints);
        if (this.userPoints >= 50) {
          this.isShowWin = true;
          setTimeout(() => {
            if (this.winMoney!== 0) {
              const innerAudioContext = uni.createInnerAudioContext();
              innerAudioContext.autoplay = false;
              innerAudioContext.src = "/static/audio/huanhu.mp3";
              innerAudioContext.play();
            } else {
              const innerAudioContext = uni.createInnerAudioContext();
              innerAudioContext.autoplay = false;
              innerAudioContext.src = "/static/audio/kexi.mp3";
              innerAudioContext.play();
            }
            this.$refs.resultPopup.open();
            this.score = addUserScore(this.winMoney);
          }, 500);
        } else {
          this.isShowWin = false;
        }
      },
      getViewHW2() {
        let info = uni.createSelectorQuery().in(this.$vm).select(".usernums");
        console.log("info: ", info);
        return new Promise((resolve, reject) => {
          info.boundingClientRect((data) => {
            console.log("data: " + JSON.stringify(data));
            this.viewWidth2 = data.width;
            this.viewHeight2 = data.height;
            resolve();
          }).exec(function(res) {
            // 注意：exec方法必须执行，即便什么也不做，否则不会获取到任何数据
          });
        });
      },
      drawLine2() {
        let point1 = this.points2[0];
        let point2 = this.points2[1];
        this.points2.shift();
        this.ctx2.moveTo(point1.x, point1.y);
        this.ctx2.lineTo(point2.x, point2.y);
        this.ctx2.stroke();
        this.ctx2.draw(true);
      },
      drawInit2() {
        this.getViewHW2().then(() => {
          this.ctx2 = uni.createCanvasContext('canvas2');
          let x = this.viewWidth2;
          let y = this.viewHeight2;
          console.log(x, y);
          // 设置 globalCompositeOperation 为 "dissolve"
          // this.ctx.value.setGlobalCompositeOperation("dissolve");
          this.ctx2.setFillStyle('#bbb');
          this.ctx2.fillRect(0, 0, x, y);
          this.ctx2.setFontSize(30);
          this.ctx2.setTextBaseline('middle');
          this.ctx2.setFillStyle('black');
          this.ctx2.setTextAlign('center');
          this.ctx2.fillText(this.title, x / 2, y / 2);
          // let image = uni.createSelectorQuery().in(this.$vm).select(".wallet");
          // this.ctx2.drawImage(image,100,100);
          this.ctx2.lineWidth = 4;
          this.ctx2.lineCap = "round";
          this.ctx2.lineJoin = "round";
          this.ctx2.draw(true);
          //接下来线的样式
          this.ctx2.lineWidth = 80; //刮的大小
          this.ctx2.lineCap = "round";
          this.ctx2.lineJoin = "round";
          this.ctx2.globalCompositeOperation = 'destination-out'; //关键是这个属性
        });
      }
    }
  };
</script>

<style lang="scss">
  @font-face {
    font-family: NumFont;
    src: url('https://mp-02da6b36-ab1b-494d-b346-d6763fb77772.cdn.bspapp.com/resource/font/HONORSans-Bold.ttf');
  }

.layout {
    width: 100%;
    height: 100vh;
    background-color: #008B8B;
    position: relative;

  .goBack {
      position: fixed;
      margin-left: 10rpx;
      width: 38px;
      height: 38px;
      background: rgba(0, 0, 0, 0.5);
      borderRadius: 50%;
      backdrop-filter: blur(10rpx);
      border: 1rpx solid rgba(255, 255, 255, 0.3);
      display: flex;
      alignItems: center;
      justifyContent: center;
      z-index: 1000;
    }

  .content {
      // width: 100%;
      height: calc(100vh - 40rpx);
      background-color: #de3018;
      marginTop: 0rpx;
      border: 20rpx solid #008B8B;
      box-sizing: content-box;
      borderRadius: 20px;
      overflow: hidden;
      position: relative;
      display: flex;
      alignItems: center;
      flex-direction: column;

    .title {
        position: relative;
        width: 100%;

      .bg {
          position: absolute;
          top: 0rpx;
          left: 0rpx;
          width: 100%;
          height: 350rpx;

        .image {
            width: 100%;
            height: 100%;
          }
        }

      .info {
          position: absolute;
          top: 0rpx;
          left: 0rpx;
          width: 100%;
          height: 350rpx;
          display: flex;
          alignItems: center;
          justifyContent: center;
          flex-direction: column;

        .title1 {
            top: 100rpx;
            width: 100%;
            fontSize: 110rpx;
            fontWeight: bold;
            textAlign: center;
            color: #008B8B;
            // color: white;
          }

        .title2 {
            width: 80%;
            fontSize: 18px;
            textAlign: center;
            color: #de3018;
            backgroundColor: #ffe21d;
            padding: 0 20rpx;
          }

        .title3 {
            width: 100%;
            marginTop: 20rpx;
            fontSize: 14px;
            textAlign: center;
            color: #ffe21d;
            padding: 0 20rpx;
          }
        }
      }

    .usernums {
        marginTop: 420rpx;
        position: relative;
        width: 95%;
        backgroundColor: #d8d7d7;
        border: 10rpx solid #008B8B;

      .items {
          width: 100%;
          height: 100%;

        .item {
            width: 100%;
            height: 100%;
            // background-color: red;
            display: flex;
            justifyContent: center;
            alignItems: center;
            flex-direction: column;

          .winnum {
              width: 200rpx;
              marginTop: 10rpx;
              fontSize: 180rpx;
              textAlign: center;
              color: "#ed2011";
              fontWeight: bold;
              -webkit-text-stroke: 1px black;
              fontFamily: 'NumFont';
            }
          }
        }

      .canvas2 {
          position: absolute;
          left: 0;
          top: 0;
          width: 100%;
          height: 100%;
        }

      }

    }
  }


.resultPopup {
    display: flex;
    flex-direction: column;
    alignItems: center;
    paddingBottom: 150rpx;

  .bg {
      background: no-repeat center;
      background-size: cover;
      position: relative;
    }

  .win {
      width: 735rpx;
      height: 986rpx;
      background-image: url('https://mp-02da6b36-ab1b-494d-b346-d6763fb77772.cdn.bspapp.com/resource/image/bg_win_2.png');
      background-size: 500rpx 655rpx;

    .text {
        line-height: 120rpx;
        textAlign: center;
        position: absolute;
        width: 100%;
        top: 605rpx;
        left: 0;
        color: #fff;
        fontSize: 40rpx;
        fontWeight: bolder;